import axios from "axios"
//引入进度条
import nProgress from "nprogress";
import "nprogress/nprogress.css"
//引入基准地址和token
import { serverUrl, getToken,remToken } from "./tools"
import { message } from "antd";
//创建一个axios实例
const instance = axios.create({
  baseURL: serverUrl,
  timeout: 5000,
});
//请求拦截
instance.interceptors.request.use(function (config) {
  //console.log(config)
  //发送请求时携带请求头
  config.headers.token = getToken();
  //启动进度条
  nProgress.start();
  return config;
}, function (error) {
  return Promise.reject(error);
});
//响应拦截
instance.interceptors.response.use(function (response) {
  //关闭进度条
  nProgress.done();
  
  return response;
}, function (error) {
 //关闭进度条
  nProgress.done();
  //验证token过期，若过期了则跳转到登录界面，并删除原有的token
  //console.log(error.code)//ERR_BAD_REQUEST
  //console.log(error.response.data.code,error.response.data.info)//0,请先登录
  if (error.code === "ERR_BAD_REQUEST") {
    message.warning(error.response.data.code)
    //清空过期的token,
    remToken();
    //清空用户名
    localStorage.removeItem("uname");
    window.location.href = "/login";
  }
  return Promise.reject(error);
});
export default instance;
export const get = (url: string, params = {}) =>
  instance.get(url, { params })
    //.then((res) => res.data);